package org.ko.core.websupport.log.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.ko.core.domain.auth.User;
import org.ko.core.domain.support.LogInfo;
import org.ko.core.logic.LogInfoService;
import org.ko.core.websupport.log.LogLevel;
import org.ko.core.websupport.log.LogWorker;
import org.springframework.util.StringUtils;

/** 
 * 全局日志等级<包日志等级<类和方法日志等级
 * @author 	<a href="mailto:ketayao@gmail.com">ketayao</a>
 * Version  2.1.0
 * @since   2013-5-3 下午4:41:55 
 */
public class Log4JDBCImpl implements LogWorker {
	
	private LogLevel rootLogLevel = LogLevel.ERROR;
	
	private LogInfoService service;
	
	private Map<String, LogLevel> customLogLevel = new HashMap<String, LogLevel>();


	public void setRootLogLevel(LogLevel rootLogLevel) {
		this.rootLogLevel = rootLogLevel;
	}

	/**   
	 * 
	 * @return  
	 * @see com.ketayao.ketacustom.log.LogTemplate#getRootLogLevel()  
	 */
	@Override
	public LogLevel getRootLogLevel() {
		return rootLogLevel;
	}
	
	public void setCustomLogLevel(Map<String, LogLevel> customLogLevel) {
		this.customLogLevel = customLogLevel;
	}
	
	@Override
	public Map<String, LogLevel> getCustomLogLevel() {
		return customLogLevel;
	}
	
	
	public void setService(LogInfoService service) {
		System.out.println(service);
		this.service = service;
	}

	@Override
	public void log(String message, LogLevel logLevel) {
		
	}

	@Override
	public void log(String message, HttpServletRequest req,String[] params, LogLevel logLevel) {
		this.log(message, req, params, logLevel, "");
	}
	
	@Override
	public void log(String message, HttpServletRequest req,String[] params, LogLevel logLevel, String category) {
		if(StringUtils.isEmpty(message)){
			return ;
		}
		
		LogInfo log = new LogInfo();
		
		/*
		 * 尝试从subject中读取登录用户的数据
		 */
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser.getPrincipal() != null){
			User user = (User)currentUser.getPrincipal();
			log.setUserId(user.getId().intValue());
			log.setUserName(user.getName());
		}
		
		for(int i=0;i<params.length;i++){
			String p = req.getParameter(params[i]);
			message = message.replace("{"+i+"}", p == null?"":p);
		}
		
		log.setRemark((String)req.getAttribute(LogInfo.REMARK));
		
		log.setCategory(category);
		log.setLevel(logLevel);
		log.setMessage(message);
		log.setDate(new Date());
		
		try {
			service.save(log);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
